﻿/*
* Activity Tracking Log v0.1.1 - http://activitytrackinglog.codeplex.com
* Activity Tracking Log for ASP.Net & ASP.Net MVC
* Copyright (c) 2011 Vadim Burac
* Licensed under the Microsoft Public License (Ms-PL)
* http://activitytrackinglog.codeplex.com/license
*/


function ActivityTrackingLog() {
    var _thisClass = this;
    var _securityKey = '{security_key}';
    var _logHandlerUrl = '{log_handler_url}';

    this.logActivityAsync = function (category, activity, activityCode, fnCallback) {
        _thisClass.logActivity(category, activity, activityCode, true, fnCallback);
    }

    this.logActivity = function (category, activity, activityCode, async, fnCallback) {
        var pageUrl = window.location.pathname;
        var queryString = window.location.search;
        var data = {
            security_key: _securityKey,
            category: category,
            activity: activity,
            activity_code: activityCode,
            page_url: pageUrl,
            query_string: queryString,
            t: Math.random()
        }

        _callServer(_logHandlerUrl, data, !!async, fnCallback);
    }

    function _callServer(handlerUrl, data, async, fnCallback) {
        var xmlhttp = _getXHR();

        // initialize xhr
        if (async) {
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    if (typeof (fnCallback) == 'function')
                        fnCallback(xmlhttp.responseText);
                }
            }
        }
        xmlhttp.open("POST", handlerUrl, async);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        var stringData = _jsonToQueryString(data);
        xmlhttp.send(stringData);
        if (!async) {
            if (typeof (fnCallback) == 'function')
                fnCallback(xmlhttp.responseText);
        }
    }

    function _getXHR() {
        var xmlhttp;
        if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        }
        else {// code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        return xmlhttp;
    }

    function _jsonToQueryString(json) {
        var queryString = "";
        for (var fieldName in json) {
            if (queryString.length > 0)
                queryString += "&";

            queryString += fieldName + "=" + json[fieldName];
        }

        return queryString;
    }
};

// initialize log proxy
var atLog = new ActivityTrackingLog();